import { defineStore } from 'pinia';

import { useChatWebSocket } from '@/pages/chat/socket.js';
import app from './app.js';
import socketIO from './utils/socket.js';
import chat2 from '@/sheep/api/chat2.js';
import chat from '@/sheep/api/chat.js';
import { getStatusBar } from '@/utils/getStatusBar.js';
// const {
// 	socketInit,
// 	state: chatData,
// 	socketSendMsg,
// 	formatChatInput,
// 	socketHistoryList,
// 	onDrop,
// 	onPaste,
// 	getFocus,
// 	// upload,
// 	getUserToken,
// 	// socketTest,
// 	showTime,
// 	formatTime,
// } = useChatWebSocket();
const getMsgType = (type, callVideo) => {
  let msgName = '[其他消息]';
  switch (type) {
    case 'image':
      msgName = '[图片]';
      break;
    case 'mp3':
      msgName = '[语音]';
      break;
    case 'mp4':
      msgName = '[视频]';
      break;
  }
  return msgName;
};
const socket = defineStore({
  id: 'socket',
  state: () => ({
    customBar: 0,
    statusBar: 0,
    socketIo: new socketIO(),
    page_font_size: 10,
    addfrienddnum: 0,
    socket: {},
  }),

  actions: {
    async init() {
      // this.socket = useChatWebSocket();
      getStatusBar();
      this.socketIo.connectSocketInit();
      this.socketIo.onMessage = this.onMessage;
      // const {
      // 	code
      // } = await this.socket.getUserToken();
      // if (code === 1) {
      // 	this.socket.socketInit(app().chat, () => {
      // 		// scrollBottom();
      // 	});
      // } else {
      // 	socketState.value.isConnect = false;
      // }
    },
    onMessage: (res) => {
      var userInfo = uni.getStorageSync('userInfo');
      let data = res.data;
      console.log('Socket接收到消息:', res, '当前连接状态:', socket().socketIo.is_open_socket, '当前用户ID:', userInfo?.id);

      // this.connect = true;
      switch (res['type']) {
        // 服务端ping客户端
        case 'ping':
          console.log('收到服务器ping请求，发送pong响应');
          this.socketIo.send({
            type: 'pong',
          });
          break;
        case 'pong':
          console.log('收到服务器pong响应，心跳正常');
          break;
        case 'system':
          console.log('收到系统消息:', res.message, '类型:', res.message.type);
          if (res.message.type === 'addfriends') {
            this.addfrienddnum = res.message.content;
            console.log('更新好友请求数量:', this.addfrienddnum);
          }
          // this.playSound()
          break;

        case 'init':
          console.log('收到初始化消息，绑定客户端ID:', res.client_id);
          chat2
            .userbind({
              client_id: res.client_id,
            })
            .then((e) => {
              console.log('客户端ID绑定成功:', e);
            });
          break;

        case 'user':
          console.log('收到用户消息:', res.message, '发送者ID:', res.form.id, '接收者ID:', res.to.id);
          if (res.to.id == userInfo.id) {
            console.log('消息是发给当前用户的，触发message_user事件');
            uni.$emit('message_user', res);
          }
          break;

        case 'group':
          console.log('收到群组消息:', res.message, '群组ID:', res.to.id);
          uni.$emit('message_group', res);
          break;

        case 'message_live':
          console.log('收到直播消息:', res.message, '直播间ID:', res.data.to, '发送者:', res.form);
          uni.$emit('message_live', res);
          break;

        default:
          console.log('收到未知类型消息:', res.type, res);
          break;
      }
    },
    playSound(msg) {
      if (uni.getSystemInfoSync().platform == 'android') {
        // 创建一个自定义通知
        var msg = plus.push.createMessage(msg.message.type === 'text' ? msg.message.content : getMsgType(msg.message.type), '', {
          cover: true,
          when: new Date(msg.createtime),
          title: '收到一条消息：',
        });

        return;
      }
    },
    scoketClose() {
      this.socketIo.connectNum = 1;
      const data = {
        type: 'close',
      };
      this.socketIo.send(data); // 这是给后端发送特定数据 关闭推送
      this.socketIo.Close(); // 主动 关闭连接 ， 不会重连
    },
    sendmsg(data) {
      return new Promise(async (res) => {
        let a = await chat2.sendmsg(data);
        res(a);
      });
    },
    async sendgroupapi(data) {
      return new Promise(async (res) => {
        let a = await chat2.groupmsg(data);
        res(a);
      });
    },
  },
});

export default socket;
